package com.lzb.yabbs.app;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AbsListView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gitonway.lee.niftynotification.lib.Effects;
import com.gitonway.lee.niftynotification.lib.NiftyNotificationView;
import com.lzb.yabbs.AppConfig;
import com.lzb.yabbs.R;
import com.lzb.yabbs.adapter.CardInfoAdapter;
import com.lzb.yabbs.dao.Card;
import com.lzb.yabbs.dao.Comment;
import com.lzb.yabbs.interfaces.GetCommentCallback;
import com.lzb.yabbs.net.GetCommentFromNet;
import com.lzb.yabbs.net.OkHttpClientRequest;
import com.lzb.yabbs.ui.SendMessageDialog;
import com.lzb.yabbs.util.PersonalData;
import com.lzb.yabbs.util.TimeManager;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import org.apache.http.message.BasicNameValuePair;

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;

public class CardInfoActivity extends AppCompatActivity implements AbsListView.OnScrollListener, View.OnClickListener {

    private final int GET_COMMENTS_EMPTY = 0x185;
    private final String TAG = getClass().getSimpleName();
    private Card card;
    private List<Comment> mComments = new ArrayList<>();
    private CardInfoAdapter mCardInfoAdapter;
    private final int GET_COMMENTS_SUCCESS = 0x123;
    private final int GET_COMMENTS_FAIL = 0x122;
    private final int REFRESH_LIST = 0x546;
    private final int COMMENT_SUCCESS = 0x157;
    private final int COMMENT_FAIL = 0x837;
    private int refre = 1;

    private int mLastScrollY;
    private int mPreviousFirstVisibleItem;
    private AbsListView mListView;

    private ListView mCardInfoLv;
    private LinearLayout mCommentLl;
    private EditText mCommentEt;
    private ImageView mSendIv;

    private SharedPreferences mSharedPreferences;
    private ProgressDialog mProgressDialog;

    private DisplayImageOptions options = new DisplayImageOptions.Builder().showImageOnLoading(null)
            .showImageOnFail(null)
            .cacheInMemory(true)
            .cacheOnDisk(true)
            .bitmapConfig(Bitmap.Config.RGB_565)
            .build();


    public MyHandler mHandler = new MyHandler(new WeakReference<Activity>(this));

    class MyHandler extends Handler {

        WeakReference<Activity> weakReference;

        public MyHandler(WeakReference<Activity> weakReference) {
            this.weakReference = weakReference;
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case GET_COMMENTS_SUCCESS:
                    Bundle data = msg.getData();
                    List<Comment> datas = data.getParcelableArrayList("comments");
                    mComments.addAll(datas);

                    mCardInfoAdapter.notifyDataSetChanged();
                    mCommentLl.setVisibility(View.VISIBLE);

                    break;
                case GET_COMMENTS_FAIL:
                    break;
                case REFRESH_LIST:

                    break;
                case COMMENT_SUCCESS:
                    if (mCardInfoAdapter.getCount() < 25) {
                        mCardInfoAdapter.clearData();
                        getComments(card.getId(), 0);
                    }
                    mCommentEt.setText("");
                    mCommentEt.clearFocus();
                    NiftyNotificationView.build(CardInfoActivity.this, "评论成功", Effects.flip, R.id.mll)
                            .setIcon(R.mipmap.ic_launcher).    //You must call this method if you use ThumbSlider effect
                            show();
                    mProgressDialog.dismiss();
                    break;
                case COMMENT_FAIL:
                    NiftyNotificationView.build(CardInfoActivity.this, "评论失败", Effects.flip, R.id.mll)
                            .setIcon(R.mipmap.ic_launcher).    //You must call this method if you use ThumbSlider effect
                            show();
                    mProgressDialog.dismiss();
                    break;
                case GET_COMMENTS_EMPTY:
                    mCommentLl.setVisibility(View.VISIBLE);
                    break;
            }
        }
    }

    ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.d(getClass().getSimpleName(), "onCreate");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_card_info);
        mSharedPreferences = getSharedPreferences("login", Context.MODE_PRIVATE);

        card = (Card) getIntent().getSerializableExtra("card");


        initView();
        restoreActionbar();

        getComments(card.getId(), 0);
    }

    private void getComments(int id, int page) {

        GetCommentFromNet.getComments(AppConfig.URL_GET_COMMENT, new GetCommentCallback() {
            @Override
            public void getCommentsSuccess(List<Comment> cards) {
                if (cards.size() > 0) {
                    Message msg = new Message();
                    msg.what = GET_COMMENTS_SUCCESS;
                    Bundle bundle = new Bundle();
                    bundle.putParcelableArrayList("comments", (ArrayList<Comment>) cards);
                    msg.setData(bundle);
                    mHandler.sendMessage(msg);
                } else {
                    mHandler.sendEmptyMessage(GET_COMMENTS_EMPTY);
                }
            }

            @Override
            public void getCommentFail(int reason) {
                mHandler.sendEmptyMessage(GET_COMMENTS_FAIL);
            }
        }, id, page);
    }

    private void initView() {
        mCardInfoLv = (ListView) findViewById(R.id.card_info_lv);
        mCommentLl = (LinearLayout) findViewById(R.id.comment_ll);
        mCommentEt = (EditText) findViewById(R.id.comment_et);
        mSendIv = (ImageView) findViewById(R.id.send_iv);

        mSendIv.setOnClickListener(this);

        View headerView = LayoutInflater.from(this).inflate(R.layout.card_info_lv_header, null);
        initHeaderViewDatas(headerView);
        mCardInfoLv.addHeaderView(headerView);

        mCardInfoAdapter = new CardInfoAdapter(this, mComments);
        mCardInfoLv.setAdapter(mCardInfoAdapter);

        setListView(mCardInfoLv);
        mCardInfoLv.setOnScrollListener(this);
    }

    private void initHeaderViewDatas(View headerView) {
        CircleImageView headerImg = (CircleImageView) headerView.findViewById(R.id.header_img_iv);
        TextView usernameTv = (TextView) headerView.findViewById(R.id.username_tv);
        TextView timeTv = (TextView) headerView.findViewById(R.id.time_tv);
        TextView commentNumTv = (TextView) headerView.findViewById(R.id.comment_num_tv);
        TextView boardTv = (TextView) headerView.findViewById(R.id.board_tv);
        TextView cardTitleTv = (TextView) headerView.findViewById(R.id.card_title_tv);
        WebView cardContentWv = (WebView) headerView.findViewById(R.id.card_content_wv);
        //HtmlTextView mHtmlTextView= (HtmlTextView) headerView.findViewById(R.id.card_content_htv);

        usernameTv.setText(card.getUsername());
        timeTv.setText(TimeManager.getTimeToNow(card.getPost_time()));
        commentNumTv.setText(card.getComment_num() + "个回复");
        boardTv.setText(card.getBoard());
        cardTitleTv.setText(card.getTitle());
        String imgUrl = card.getAvatar();
        if (null == imgUrl || imgUrl.equals("") || imgUrl.equals("null"))
            ImageLoader.getInstance().displayImage(AppConfig.MO_REN_avatar, headerImg, options);
        else
            ImageLoader.getInstance().displayImage(card.getAvatar(), headerImg, options);
        if (!TextUtils.isEmpty(card.getPost_content())) {
            cardContentWv.loadDataWithBaseURL(null, card.getPost_content(), AppConfig.mimeType, AppConfig.encoding, null);
            cardContentWv.setWebViewClient(new WebViewClient() {
                @Override
                public void onPageFinished(WebView view, String url) {
                    super.onPageFinished(view, url);
                    Log.d(TAG, "onPageFinished:" + card.getPost_content());
                }
            });
        } else
            cardContentWv.setVisibility(View.GONE);

        headerImg.setOnClickListener(this);
        //mHtmlTextView.setHtmlFromString(card.getPost_content(),new HtmlTextView.LocalImageGetter());
    }

    private void restoreActionbar() {
        ActionBar actionBar = getSupportActionBar();
        actionBar.setHomeButtonEnabled(true);
        actionBar.setDisplayShowTitleEnabled(true);
        actionBar.setTitle(card.getTitle());
        actionBar.setDisplayHomeAsUpEnabled(true);
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {

    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        if (totalItemCount == 0) return;
        if (isSameRow(firstVisibleItem)) {
            int newScrollY = getTopItemScrollY();
            boolean isSignificantDelta = Math.abs(mLastScrollY - newScrollY) > getResources().getDimensionPixelOffset(R.dimen.fab_scroll_threshold);
            if (isSignificantDelta) {
                if (mLastScrollY > newScrollY) {
                    onScrollUp();
                } else {
                    onScrollDown();
                }
            }
            mLastScrollY = newScrollY;
        } else {
            if (firstVisibleItem > mPreviousFirstVisibleItem) {
                onScrollUp();
            } else {
                onScrollDown();
            }

            mLastScrollY = getTopItemScrollY();
            mPreviousFirstVisibleItem = firstVisibleItem;
        }
    }

    private void onScrollDown() {
        if (View.GONE == mCommentLl.getVisibility()) {
            Animation animation = AnimationUtils.loadAnimation(this, R.anim.comment_layout_anim_in);
            animation.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {

                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    mCommentLl.setVisibility(View.VISIBLE);
                }

                @Override
                public void onAnimationRepeat(Animation animation) {

                }
            });
            mCommentLl.startAnimation(animation);
        }
        Log.d(TAG, "onScrollDown");
    }

    private void onScrollUp() {
        if (View.VISIBLE == mCommentLl.getVisibility()) {
            Animation animation = AnimationUtils.loadAnimation(this, R.anim.comment_layout_anim_out);
            animation.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {

                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    mCommentLl.setVisibility(View.GONE);
                }

                @Override
                public void onAnimationRepeat(Animation animation) {

                }
            });
            mCommentLl.startAnimation(animation);

        }
        Log.d(TAG, "onScrollUp");
    }

    private boolean isSameRow(int firstVisibleItem) {
        return firstVisibleItem == mPreviousFirstVisibleItem;
    }

    public void setListView(@NonNull AbsListView listView) {
        mListView = listView;
    }

    private int getTopItemScrollY() {
        if (mListView == null || mListView.getChildAt(0) == null) return 0;
        View topChild = mListView.getChildAt(0);
        return topChild.getTop();
    }

    @Override
    public void onClick(View v) {
        if (R.id.send_iv == v.getId()) {
            if (mSharedPreferences.getBoolean("login", false)) {
                mProgressDialog = new ProgressDialog(this);
                mProgressDialog.setTitle("正在评论...");
                mProgressDialog.show();
                List<BasicNameValuePair> pairs = new ArrayList<>();
                int uid = mSharedPreferences.getInt("uid", 0);
                BasicNameValuePair uidPair = new BasicNameValuePair("uid", uid + "");
                String token = mSharedPreferences.getString("token", null);
                BasicNameValuePair tokenPair = new BasicNameValuePair("token", token);
                String content = mCommentEt.getText().toString();
                BasicNameValuePair contentPair = new BasicNameValuePair("content", content);
                int post_id = card.getId();
                BasicNameValuePair post_idPair = new BasicNameValuePair("post_id", post_id + "");
                pairs.add(uidPair);
                pairs.add(tokenPair);
                pairs.add(contentPair);
                pairs.add(post_idPair);
                OkHttpClientRequest.requestGet(AppConfig.URL_SEND_COMMENT, pairs, new Callback() {
                    @Override
                    public void onFailure(Request request, IOException e) {
                        mHandler.sendEmptyMessage(COMMENT_FAIL);
                    }

                    @Override
                    public void onResponse(Response response) throws IOException {
                        String resultStr = response.body().string();
                        JSONObject obj = JSON.parseObject(resultStr);
                        if (obj.getInteger("code") != 0) {
                            mHandler.sendEmptyMessage(COMMENT_SUCCESS);
                        } else {
                            mHandler.sendEmptyMessage(COMMENT_FAIL);
                        }
                    }
                });
            } else {
                NiftyNotificationView.build(CardInfoActivity.this, "请先登录", Effects.flip, R.id.mll)
                        .setIcon(R.mipmap.ic_launcher).    //You must call this method if you use ThumbSlider effect
                        show();
            }
        }else if(R.id.header_img_iv==v.getId()){
            if(PersonalData.isLogin(this)) {
                SendMessageDialog sendMessageDialog = new SendMessageDialog(this, card.getUsername(), card.getUid());
                sendMessageDialog.show();
            }else {
                NiftyNotificationView.build(this, getString(R.string.to_login_str), Effects.flip, R.id.mll)
                        .setIcon(R.mipmap.ic_launcher).    //You must call this method if you use ThumbSlider effect
                        show();
            }
        }
    }
}

